<template>
  <el-upload
    class="upload-demo"
    ref="upload"
    :action="actionUrl"
    :on-remove="handleRemove"
    :file-list="fileList"
    :auto-upload="false"
    :on-success="updataSuccess"
  >
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-button
      style="margin-left: 10px"
      size="small"
      type="success"
      @click="submitUpload"
      >上传到服务器</el-button
    >
    <div slot="tip" class="el-upload__tip">文件名</div>
  </el-upload>
</template>

<script>
import base from "../../api/config";

export default {
  name: "Updata",
  data() {
    return {
      fileList: [],
      actionUrl: base.baseUrl + base.upload,
    };
  },
  methods: {
    // 上传图片的实现
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove() {
      // console.log(file, fileList);
    },
    /**
     * 上传图片到后台(服务器) 成功回调函数
     */
    updataSuccess(response) {
      // console.log(response); // imgUrl
      let index = response.url.indexOf("\\");
      let imgUrl = base.baseUrl + "/" + response.url.slice(index + 1);

      this.$emit("uploadImage", imgUrl);
      // 上传成功 清除选取文件
      // 1. 调用清除事件
      // this.$refs.upload.handleRemove();
      // 设置存储文件为空
      this.fileList = [];
    },
  },
};
</script>

<style lang="less" scoped>
</style>